<template>
  <PerfectTableComponent
    :loadTableList="loadTableList"
    :changePageSize="changePageSize"
    :changePage="changePage"
    :removeQueryField="removeQueryField"
    :clearQuery="clearQuery"
    v-model:query="query"
    title="库区"
    ref="tableRef"
    :queryFormHeaders="queryFormHeaders"
    :table="table"
    :tableColumns="tableColumns"
    :showTableIndex="false"
    :operatorColumnWidth="300"
    :baseUrl="urls.API_URL_BACKSTAGE_WMS_WMSWAREHOUSEAREA"
    v-model:form="form"
    :formHeader="formHeader"
    @beforeAddRow="beforeAddRow"
    @afterLoadDataSuccessInEditRow="afterLoadDataSuccessInEditRow"
    @beforeFormSubmit="beforeFormSubmit"
  >
    <!-----------------------------表格自定义列----------------------------------------->
    <!--仓库-->
    <template #table_column_warehouseName="scope: any">
      {{ scope.row.warehouse != null ? scope.row.warehouse.name : '' }}
    </template>
    <!-- 库位-->
    <template #table_column_seatNumber="scope: any">
      <el-link
        type="primary"
        @click="
          router.push({
            path: '/backstage/wms/warehouseSeat',
            query: {
              warehouseAreaId: scope.row.id
            }
          })
        "
        >{{ scope.row.seatNumber }}</el-link
      >
    </template>
    <!-----------------------------表格自定义列（操作列）----------------------------------------->
    <template #table_operator_left="scope">
      <el-button
        @click="
          router.push({
            path: '/backstage/wms/warehouseSeat',
            query: {
              warehouseAreaId: scope.row.id
            }
          })
        "
        type="primary"
        size="small"
        icon="House"
        plain
        >库位</el-button
      >
    </template>
  </PerfectTableComponent>
</template>

<script setup lang="ts">
import PerfectTableComponent from '@/components/base/table/PerfectTableComponent.vue';
import { nextTick, onMounted, provide, reactive, ref } from 'vue';
import useTableList from '@/api/hooks/useTableList';
import type { FormHeader, ResponseData, TableColumn } from '@/types/interface/base_interface';
import urls from '@/api/request/urls';
import { getDict } from '@/api/dict';
import type { WarehouseArea } from '@/types/interface/wms_interface';
import Request from '@/api/request/request';
// 导入路由
import { useRouter, useRoute } from 'vue-router';
const router = useRouter(); // 创建路由对象
const route = useRoute();

// 表格工具必备参数。这里为了等待仓库模块传递过来的参数，选择延迟加载
const { table, query, loadTableList, removeQueryField, clearQuery, changePageSize, changePage } = useTableList(
  urls.API_URL_BACKSTAGE_WMS_WMSWAREHOUSEAREA,
  true,
  {},
  false
);
// 将表格刷新函数传到子容器
provide('loadTableList', loadTableList);

//获取仓库模块传递过来的仓库id（如果是从仓库模块跳转来的）
const warehouseIdOfParam: string | undefined = route.query.warehouseId as string | undefined;
//赋值给query值
if (typeof warehouseIdOfParam != 'undefined' && warehouseIdOfParam != null && warehouseIdOfParam.length > 0) {
  query.value['warehouse.id'] = warehouseIdOfParam;
}
//执行查询，刷新表格
loadTableList();

//查询==========================================================
const queryFormHeaders = ref<FormHeader[]>([]);

//表格==========================================================
// 表格插件ref对象1
const tableRef = ref();

//表格列
// 定义表格所有的列字段信息
const tableColumns = ref<TableColumn[]>([]);

//表单==========================================================
//表单对象
const form = ref<WarehouseArea>({});
//表单元素类型
const formHeader = ref<FormHeader[]>([]);

const getWmsWarehouse = async () => {
  const resData: any = await new Request(urls.API_URL_BACKSTAGE_WMS_WMSWAREHOUSE + '/all').get();
  if (resData.success) {
    return resData.data;
  }
};
onMounted(async () => {
  //获取仓库列表
  const warehouses = await getWmsWarehouse();
  //定义优先级选项。放在mounted中执行时，要将引用改变量的属性也放进来。
  const enabledDict = await getDict('启用状态', 'boolean');
  queryFormHeaders.value = [
    // 查询表单
    {
      prop: 'name',
      label: '库位名称'
    },
    {
      prop: 'warehouseId',
      propAsName: 'warehouse.id',
      label: '所属仓库',
      type: 'selectObject',
      list: warehouses,
      config: {
        valueKey: 'id',
        defaultProp: {
          value: 'id',
          label: 'name'
        }
      }
    },
    {
      prop: 'enabled',
      label: '是否启用',
      type: 'select',
      list: enabledDict
    }
  ];
  //表格对象
  tableColumns.value = [
    {
      label: '库区编码',
      prop: 'code',
      width: 100,
      fixed: true
    },
    {
      label: '库区名称',
      prop: 'name',
      fixed: true
    },
    {
      label: '所属仓库',
      prop: 'warehouseName',
      type: 'custom',
      width: 100
    },
    {
      label: '库位数量',
      prop: 'seatNumber',
      type: 'custom'
    },
    {
      label: '物料存储位',
      prop: 'materialInventoryDetailNumber',
      width: 100
    },
    {
      label: '启用状态',
      prop: 'enabled',
      width: 100,
      type: 'dict',
      dict: enabledDict
    },
    {
      label: '创建时间',
      prop: 'createTime',
      width: 180
    },
    {
      label: '最后编辑时间',
      prop: 'updateTime',
      width: 180
    }
  ];
  // 添加编辑表单
  formHeader.value = [
    {
      prop: 'warehouseId',
      label: '所属仓库',
      type: 'selectObject',
      list: warehouses,
      config: {
        valueKey: 'id',
        defaultProp: {
          value: 'id',
          label: 'name'
        }
      },
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '库区编码',
      prop: 'code',
      rules: [
        {
          max: 50,
          message: '长度在不能超过50个字符',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '库区名称',
      prop: 'name',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        },
        {
          max: 30,
          message: '长度不能超过30个字符',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '是否启用',
      prop: 'enabled',
      type: 'select',
      list: enabledDict,
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    }
  ];
});
//在添加行的动作以前
const beforeAddRow = async () => {
  //传入初始值
  form.value = {
    enabled: true
  };
  //如果从仓库传递了默认值过来
  if (typeof warehouseIdOfParam != 'undefined' && warehouseIdOfParam != null && warehouseIdOfParam.length > 0) {
    //并且后面没有重新在查询栏更换默认仓库的值（如果更换了就应该是不再使用原来的仓库），则默认创建的仓库就是该仓库
    if (warehouseIdOfParam === query.value['warehouse.id']) {
      form.value.warehouseId = warehouseIdOfParam;
    }
  }
  await nextTick();
};
//在编辑行读取后端记录后需要修改的地方
const afterLoadDataSuccessInEditRow = async (formEdit: WarehouseArea) => {
  //重新封装表单对象的值
  if (formEdit.warehouse != null) {
    formEdit.warehouseId = formEdit.warehouse.id;
  }
};
//在表单提交前对对象进行封装
const beforeFormSubmit = () => {
  if (form.value.warehouseId != null) {
    form.value.warehouse = {
      id: form.value.warehouseId
    };
  }
};
</script>

<style scoped></style>
